package com.jubaozan.framework.sentinel.listener;

import com.alibaba.csp.sentinel.property.PropertyListener;
import com.jubaozan.framework.sentinel.config.ApplicationRedisValueConfig;
import com.jubaozan.framework.sentinel.constant.RuleKeyConstant;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import java.util.List;
import javax.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author jiangjinwu
 * @version 1.0
 * @since 2025/7/15 13:57
 */

@Slf4j
@Component
public abstract class AbstractRulePropertyListener<T> implements PropertyListener<List<T>> {

    @Autowired
    private ApplicationRedisValueConfig applicationRedisValueConfig;
    @Autowired
    RedisRulePublisher redisRulePublisher;
    protected RedisClient client;
    private final Class<T> ruleType;

    @Autowired
    protected RuleKeyConstant ruleKeyConstant;

    public AbstractRulePropertyListener(Class<T> ruleType) {
        this.ruleType = ruleType;
    }
    @PostConstruct
    public void  init() {
        RedisURI redisURI =  RedisURI.builder().withHost(applicationRedisValueConfig.getHost())
            .withPort(applicationRedisValueConfig.getPort())
            .withPassword(applicationRedisValueConfig.getPassword())
            .withDatabase(applicationRedisValueConfig.getDatabase())
            .build();
        client = RedisClient.create(redisURI);
    }
    @Override
    public void configUpdate(List<T> value) {
        // 公共逻辑：推送至 Redis
        redisRulePublisher.pushRules(value, getRedisKey());
        doLoad(value);
        log.info("接收到 {} 配置变更: {}", ruleType.getSimpleName(), value);
    }

    @Override
    public void configLoad(List<T> conf) {
        // 调用具体子类实现的加载逻辑
        doLoad(conf);
    }

    protected abstract void doLoad(List<T> conf);

    protected abstract String   getRedisKey();
}
